package ink.carnation.imtalk.controller;

import com.sun.mail.imap.protocol.IMAPReferralException;
import ink.carnation.imtalk.aspect.IMLogAspect;
import ink.carnation.imtalk.exception.ArgumentException;
import ink.carnation.imtalk.exception.AuthorizationException;
import ink.carnation.imtalk.exception.IMException;
import ink.carnation.imtalk.exception.LimitException;
import ink.carnation.imtalk.model.IMResult;
import ink.carnation.imtalk.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * @author flbu920
 * @date 2020/9/20 22:56
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(LimitException.class)
    public IMResult handlerLimitException(LimitException e, HttpServletRequest request) {
        log.error("msg:{},url:{},IP:{}", e.getMessage(), request.getRequestURL(), IPUtils.getIpAddress(request));
        return IMResult.failure("系统繁忙，请稍后再试");
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public IMResult handlerValidatedException(ValidationException exception) {
        return IMResult.failure(exception.getMessage());
    }

    @ExceptionHandler(ArgumentException.class)
    public IMException handleArgumentException(ArgumentException ex) {
        return ex;
    }

    @ExceptionHandler(value = AuthorizationException.class)
    public IMException authorizationHandler(AuthorizationException e) {
        return e;
    }

    @ExceptionHandler(value = Exception.class)
    public IMException exception(Exception e) {
        return new IMException("服务器异常",500);
    }
}
